import requests
from bs4 import BeautifulSoup


def parse_iptv_list(ip, port):
    # 以下两个地址都可用
    url = f"http://foodieguide.com/iptvsearch/lixtall.php?s={ip}:{port}&y=y"
    url = f"https://tonkiang.us/listall.php?s={ip}:{port}&c=false"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Referer": "http://foodieguide.com/iptvsearch/",
    }

    try:
        response = requests.get(url, headers=headers, timeout=60)
        response.raise_for_status()
        if response.status_code == 200:
            return response.text

        return None

    except requests.RequestException as e:
        return {"error": str(e)}


def html_to_m3u8(html_content, output_file):
    # 初始化分组字典
    groups = {
        "央视": [],
        "卫视": [],
        "地方": [],
        "影视": [],
        "购物": [],
        "直播": [],
        "天翼高清": [],
        "其他": []
    }

    # 解析HTML
    soup = BeautifulSoup(html_content, 'html.parser')

    # 提取所有频道块
    channel_blocks = soup.find_all('div', class_='result')

    for block in channel_blocks:
        # 提取频道名称
        channel_name_div = block.find('div', style="float: left;")
        if not channel_name_div:
            continue

        channel_name = channel_name_div.text.strip()

        # 提取频道URL
        m3u8_url = None
        m3u8_table = block.find('table', class_='tables')
        if m3u8_table:
            m3u8_url = m3u8_table.find('td', style="padding-left: 6px;").text.strip()

        if not m3u8_url:
            continue

        # 自动分类
        if "画中画" in channel_name or "单音轨" in channel_name:
            continue

        if "CCTV" in channel_name:
            group = "央视"
        elif "卫视" in channel_name or "TV" in channel_name:
            group = "卫视"
        elif "陕西" in channel_name or "陕" in channel_name or "西安" in channel_name:
            group = "地方"
        elif "四川" in channel_name or "川" in channel_name or "成都" in channel_name:
            group = "地方"
        elif "浙江" in channel_name or "浙" in channel_name or "杭州" in channel_name:
            group = "地方"
        elif ("电影" in channel_name or "影视" in channel_name or "CHC" in channel_name or "剧场" in channel_name
              or "影院" in channel_name or "院线" in channel_name or "大片" in channel_name):
            group = "影视"
        elif "直播" in channel_name:
            group = "直播"
        elif "天翼" in channel_name:
            group = "天翼高清"
        elif "购物" in channel_name:
            group = "购物"
        else:
            group = "其他"

        # 添加到对应分组
        groups[group].append((channel_name, m3u8_url))

    # 写入M3U8文件
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write("#EXTM3U\n")
        f.write("#EXT-X-VERSION:3\n")
        f.write("#EXT-X-MEDIA-SEQUENCE:0\n")
        f.write("#EXT-X-TARGETDURATION:10\n\n")

        for group_name, channels in groups.items():
            if not channels:
                continue

            f.write(f"############ {group_name}频道 ############\n")

            for name, url in channels:
                f.write(f'#EXTINF:-1 tvg-id="{name}" tvg-name="{name}" group-title="{group_name}",{name}\n')
                f.write(f"{url}\n\n")


# 使用示例
if __name__ == "__main__":
    # 从远端读取HTML内容
    IP = "nas.xlnas.com"
    port = "4022"
    html_content = parse_iptv_list(IP, port)

    # 转换为M3U8
    file_name = f'四川电信_{IP}_{port}_IPTV.m3u'
    html_to_m3u8(html_content, file_name)
    print(f"转换完成，结果已保存到 {file_name}")
